#include "../include/SerialCommunication.h"
#include <QDebug>

SerialCommunication::SerialCommunication(QObject *parent)
        : QObject(parent), serialPort(new QSerialPort(this)), isSerialPortOpen(false)
{
    // Set serial port parameters
    serialPort->setPortName("COM3");
    serialPort->setBaudRate(QSerialPort::Baud9600);
    serialPort->setDataBits(QSerialPort::Data8);
    serialPort->setParity(QSerialPort::NoParity);
    serialPort->setStopBits(QSerialPort::OneStop);
}

SerialCommunication::~SerialCommunication()
{
    closeSerialPort();
}

bool SerialCommunication::openSerialPort()
{
    if (!isSerialPortOpen)
    {
        if (serialPort->open(QIODevice::ReadWrite))
        {
            qDebug() << "Serial port opened successfully.";
            isSerialPortOpen = true;
        }
        else
        {
            qDebug() << "Failed to open serial port.";
        }
    }

    return isSerialPortOpen;
}

void SerialCommunication::closeSerialPort()
{
    if (isSerialPortOpen)
    {
        serialPort->close();
        qDebug() << "Serial port closed.";
        isSerialPortOpen = false;
    }
}

bool SerialCommunication::writeData(const QByteArray &data)
{
    if (openSerialPort())
    {
        qint64 bytesWritten = serialPort->write(data);
        return bytesWritten == data.size();
    }

    return false;
}

QByteArray SerialCommunication::readAllData()
{

    return  serialPort->readAll();
}